from django import forms
from django.core import validators
from .models import Article

"""留言板模型"""
class MessageBoardForm(forms.Form):
    title = forms.CharField(min_length=2, max_length=20,label="输入你的标题: ",
                           error_messages={"min_length":"标题的最小长度不能少于2 ！",
                                           "max_length":"标题的最大长度不能多余于20 !"})
    content = forms.CharField(widget=forms.Textarea,label="请输入你的内容: ")
    email   = forms.EmailField(label="请输入你的邮箱: ")

"""注册手机号模型"""
class RegisterForm(forms.Form):
    telephone = forms.CharField(validators=[validators.RegexValidator(r'1[345678]\d{9}',message='手机号格式不正确！')])
    pwd1 = forms.CharField(min_length=6,max_length=16)
    pwd2 = forms.CharField(min_length=6,max_length=16)
    ## 对字段进行自定义验证
    #def clean_telephone(self):
        #telephone = self.cleaned_data.get('telephone')
        ## exists = User.objects.filter(telephone=telephone).exists()
        ## if exists:
        ##     raise forms.ValidationError("手机号码已存在")
        ##return telephone
    ## 密码比对
    def clean(self):
        cleaned_data = super().clean()
        ## 获取验证后的字段
        pwd1 = cleaned_data.get("pwd1")
        pwd2 = cleaned_data.get("pwd2")
        if pwd1 == pwd2:
            return cleaned_data
        else:
            raise forms.ValidationError("表单验证失败,两次密码不一致！")

#### 继承 models.py 中的 Article 类
class ArticleForm(forms.ModelForm):
    ## 定义元数据
    class Meta:
        model = Article
        fields = "__all__"  ## 继承所有字段
        error_messages = {
            'category':{
                'required':'category 字段不能为空!'
            },
            'content':{
                'required':'content 字段不能为空！'},
            'title':{
                'required':'title 字段不能为空!'}
        }


